<template>
  <div :class="$style.root" style="background: #fff">
    <div :class="$style.lineTop">
      <div style="display: flex;align-items: center">
        <img src="@/assets/images/head/logo.png" style="width: 45px;height: 45px" alt="">
        <h1  :class="$style.invertedTitle">上海交大海洋水下工程科学研究院</h1>
<!--        <img src="@/assets/images/head/title.png" style="width: 550px;height: 25px" alt="">-->

      </div>

      <div style="margin-left: auto;display: flex">
        <div :class="$style.showTime">
          <span style="font-size: 23px;font-weight: 700">{{ currentTime }}</span>
          <span style="font-size: 18px">{{ formattedDate }}</span>
        </div>
        <div :class="$style.userInfo">
          <el-dropdown trigger="click">
            <div :class="$style.username"> {{ greeting }}</div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="showDownloadDialog">APP下载</el-dropdown-item>
                <el-dropdown-item @click="changePassword(true)">修改密码</el-dropdown-item>
<!--                <el-dropdown-item>-->
                <!--                  <div style="display: flex;flex-direction: column">-->
                <!--                    <div style="display: flex;align-items: center">-->
                <!--                      默认打印机-->
                <!--                      <el-button style="margin-left: 5px;text-decoration: underline" size="mini" type="text"-->
                <!--                                 @click="printShow">更改-->
                <!--                      </el-button>-->
                <!--                      <el-button v-if="printOv.printerName" style="color: #f00;text-decoration: underline" size="mini"-->
                <!--                                 type="text" @click="printDel">-->
                <!--                        删除-->
                <!--                      </el-button>-->
                <!--                    </div>-->
                <!--                    <div v-if="printOv.printerName">{{ printOv.printerName }}</div>-->
                <!--                  </div>-->
                <!--                </el-dropdown-item>-->
                <el-dropdown-item>当前版本：V 2.0.17</el-dropdown-item>
<!--                <el-dropdown-item @click="upLoadApp" v-if="JSON.parse(userVO).username==='admin'">APP版本更新-->
<!--                </el-dropdown-item>-->
                <el-dropdown-item @click="outLogin">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <div :class="$style.menuContainer">
      <div style="color: #333;font-size: 20px;font-weight: 700;padding:0 20px;width: 190px">
        MES管理系统
      </div>
      <el-icon color="#999" v-if="!scrollLeftDisabled" :class="$style.scrollButton" @click="scrollMenu(-100)">
        <ArrowLeftBold/>
      </el-icon>
      <div :class="$style.menuWrapper" ref="menuWrapper">
        <div :class="$style.menuContent" ref="menuContent">
          <div v-for="(item, index) in routerData" :key="index">
            <!--            v-if="roleRouteList.some(role => role.urlPath === item.path)"-->
            <div :class="$style.route">
              <div style="cursor: pointer;" @click="toPath(item.redirect, item.path)"
                   :class="isActive(item.path) ? $style.active : ''"> {{ item.title }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-icon color="#999" v-if="!scrollRightDisabled" :class="$style.scrollButton" style="margin-left: 10px"
               @click="scrollMenu(100)">
        <ArrowRightBold/>
      </el-icon>
    </div>


    <el-dialog v-model="showDownload" title="扫码下载APP" width="600px">
      <div style="width: 500px;height: 350px;display: flex;align-items: center;justify-content: center;margin: 0 auto">
        <img src="@/assets/images/download.png" style="width: 300px;height:300px">
      </div>
    </el-dialog>

    <el-dialog v-model="showPrint" title="网络打印机" width="1200px">
      <el-table :data="printData" height="500px" style="width: 100%">
        <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
        <el-table-column prop="printerCode" label="打印机编号" align="center" width="100"></el-table-column>
        <el-table-column prop="printerName" label="打印机描述" align="center" width="100"></el-table-column>
        <el-table-column prop="printerModel" label="打印机型号" align="center" width="150"></el-table-column>
        <el-table-column prop="printerServerIp" label="打印服务地址" align="center" width="350"></el-table-column>
        <el-table-column prop="printerIp" label="打印机ip" align="center" width="150"></el-table-column>
        <el-table-column prop="printerPort" label="端口" align="center" width="150"></el-table-column>
        <el-table-column prop="printerDpi" label="分辨率" align="center" width="150"></el-table-column>
        <el-table-column prop="paperWidth" label="纸张宽" align="center" width="150"></el-table-column>
        <el-table-column prop="paperHeight" label="纸张高" align="center" width="150"></el-table-column>
        <el-table-column prop="paperGap" label="纸张间隔" align="center" width="150"></el-table-column>
        <el-table-column prop="paperX" label="边框距" align="center" width="150"></el-table-column>
        <el-table-column prop="paperY" label="边框高" align="center" width="150"></el-table-column>
        <el-table-column prop="fileFormat" label="打印文件格式" align="center" width="150"></el-table-column>
        <el-table-column prop="isEnable" label="是否启用" align="center" width="150">
          <template #default="scope">
            {{ scope.row.isEnable == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="index" label="操作" align="center" fixed="right" width="150">
          <template #default="scope">
            <el-button type="text" icon="DocumentCopy" @click="defaultPrint(scope.row)">
              设为默认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref, watch, onBeforeUnmount} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import axiosInstance from '@/utils/http/api';
import {ElMessage, ElMessageBox} from 'element-plus';
import {ArrowLeftBold, ArrowRightBold} from '@element-plus/icons-vue';

onMounted(() => {
  updateTime(); // 立即执行一次
  timer = setInterval(updateTime, 1000); // 每秒更新
  // const userVO = localStorage.getItem('userVO');
  // if (JSON.parse(userVO).password === '352a8e179fd2a71b61623847ffaa57c8') {
  //   changePassword(false);
  // }
});

onBeforeUnmount(() => {
  clearInterval(timer); // 清理定时器
});

const username = localStorage.getItem('username');

const greeting = computed(() => `您好 !\n${username}`);

const currentTime = ref('');
const formattedDate = ref('');
const updateTime = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒数补零

  formattedDate.value = `${year}年${month}月${day}日`;
  currentTime.value = `${hours}:${minutes}:${seconds}`; // 输出格式如 "14:05:09"
};

let timer;

const menuWrapper = ref<HTMLElement | null>(null);
const menuContent = ref<HTMLElement | null>(null);
const scrollLeftDisabled = ref(true);
const scrollRightDisabled = ref(false);

const scrollMenu = (scrollAmount: number) => {
  if (menuWrapper.value && menuContent.value) {
    const newScrollLeft = menuWrapper.value.scrollLeft + scrollAmount;
    menuWrapper.value.scrollLeft = newScrollLeft;

    scrollLeftDisabled.value = newScrollLeft <= 0;
    scrollRightDisabled.value = newScrollLeft >= (menuContent.value.scrollWidth - menuWrapper.value.clientWidth);
  }
};

watch(() => menuWrapper.value?.scrollLeft, (newScrollLeft) => {
  if (menuWrapper.value && menuContent.value) {
    scrollLeftDisabled.value = newScrollLeft <= 0;
    scrollRightDisabled.value = newScrollLeft >= (menuContent.value.scrollWidth - menuWrapper.value.clientWidth);
  }
});

const router = useRouter();
const routerData = router.options.routes.filter(item => !item.noMenu).sort((a, b) => a.sort - b.sort);
console.log(routerData,'routerDatarouterData')
const roleRoute = ref(localStorage.getItem('roleRouteList') || '[]');
let roleRouteList = ref([]);
const showDownload = ref(false);
try {
  roleRouteList.value = JSON.parse(roleRoute.value);
} catch (error) {
  roleRouteList.value = [];
}

const list = ref([routerData]);
const route = useRoute();
const activePath = window.location.pathname;

const changePassword = (firstPass) => {
  const canDo = firstPass;
  const title = canDo ? '请输入新密码' : '首次登录请修改密码';
  ElMessageBox.prompt(title, '修改密码', {
    confirmButtonText: '确认',
    showClose: canDo,
    showCancelButton: canDo,
    closeOnClickModal: canDo,
    closeOnPressEscape: canDo,
    inputValidator: (value) => {
      if (value.length < 6) {
        return '密码长度不能少于6位';
      }

      if (value === 'Lg@pames2025!') {
        return '密码不能为默认密码';
      }

      if (!/[a-z]/.test(value)) {
        return '密码必须包含英文字母';
      }
      if (!/[0-9]/.test(value)) {
        return '密码必须包含阿拉伯数字';
      }

      if (/(012|123|234|345|456|567|678|789|890)/.test(value)) {
        return '数字不允许连续三位以上';
      }
      return true;
    },
    inputErrorMessage: '密码不符合要求'
  })
      .then(({value}) => {
        const userVO = JSON.parse(localStorage.getItem('userVO'));
        axiosInstance.post('/api/basedataUser/updatePassword', {
          password: value,
          id: userVO.id
        }).then(res => {
          userVO.password = value;
          localStorage.setItem('userVO', JSON.stringify(userVO));
          ElMessage.success('密码修改成功');
        });
      });
};

const windowPath = ref(window.location.pathname);
watch(
    () => activePath,
    (newPath) => {
      // Handle route change logic here
    }
);

// const userVO = localStorage.getItem('userVO');
const userVO = ref(null)

const printOv = ref({});

onMounted(() => {
  try {
    const parsedUserVO = JSON.parse(userVO);
    if (parsedUserVO && 'printerSetting' in parsedUserVO) {
      printOv.value = parsedUserVO.printerSetting;
    } else {
      printOv.value = {};
    }
  } catch (error) {
    printOv.value = {};
  }
});


const showDownloadDialog = () => {
  showDownload.value = true;
};

const defaultPrint = (row) => {
  const userVO = JSON.parse(localStorage.getItem('userVO'));
  userVO.printerSetting = row;

  axiosInstance.put('/api/basedataUser/update', userVO).then(res => {
    ElMessage.success('设置成功!');
    showPrint.value = false;
    printOv.value = row;
    localStorage.setItem('userVO', JSON.stringify(userVO));
  });
};

const outLogin = () => {
  ElMessageBox.confirm(
      '确认退出登录吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => {
        axiosInstance.post('/api/basedataAuth/signOut', {}).finally(res => {
          localStorage.removeItem('token');
          router.push('/home/login');
        });
      });
};

const printData = ref([]);
const showPrint = ref(false);
const printShow = () => {
  axiosInstance.post('/api/tmPrinterSetting/getPage', {page: 1, pageSize: 999}).then(res => {
    printData.value = res.data.records;
  });
  showPrint.value = true;
};

const printDel = () => {
  ElMessageBox.confirm(
      '确认删除吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => {
        const userVO = JSON.parse(localStorage.getItem('userVO'));
        userVO.printerSetting = null;

        axiosInstance.put('/api/basedataUser/update', userVO).then(res => {
          ElMessage.success('设置成功!');
          showPrint.value = false;
          printOv.value = {};
          localStorage.setItem('userVO', JSON.stringify(userVO));
        });
      });
};

const cersion = ref(null);

const upLoadApp = () => {
  axiosInstance.get('/api/cersion/check', {
    params: {}
  }).then(res => {
    cersion.value = res.data;
    ElMessageBox.prompt('当前版本:' + cersion.value, '更新版本', {
      confirmButtonText: 'OK'
    })
        .then(({value}) => {
          axiosInstance.get('/api/cersion/update', {
            params: {
              version: value
            }
          }).then(res => {
            ElMessage.success('成功');
          });
        });
  });
};

// 预处理路由映射（应在应用初始化时执行一次）
const routerMap = new Map(routerData.map(route => [route.path, route]));
let roleRouteMap: Map<string, any>;

const updateRoleRouteMap = () => {
  try {
    const roleData = JSON.parse(localStorage.getItem('roleRouteJSON') || '[]');
    roleRouteMap = new Map(roleData.map(route => [route.urlPath, route]));
  } catch {
    roleRouteMap = new Map();
  }
};

// 核心跳转逻辑优化
const toPath = (path: string, url: string) => {
    router.push(path || url || '/404').catch((error) => {
      console.error('Navigation failed:', error);
      router.push('/error');
    });

  return false
  // 1. 更新并获取最新权限路由
  updateRoleRouteMap();

  // 2. 快速查找路由配置
  const roleRoute = roleRouteMap.get(url);
  const routerConfig = routerMap.get(url);

  // 3. 安全获取子路由
  const roleChildren = roleRoute?.children || [];
  const routerChildren = routerConfig?.children || [];

  // 4. 使用哈希表加速匹配
  const roleChildrenMap = new Map(roleChildren.map(child => [child.urlPath, child]));

  // 5. 查找第一个有效子路由（包含递归查找）
  const findValidChild = (children: any[]): any => {
    for (const child of children) {
      if (child.component) return child;
      if (child.children?.length) {
        const nestedChild = findValidChild(child.children);
        if (nestedChild) return nestedChild;
      }
    }
    return null;
  };

  // 6. 优先匹配权限路由和本地配置的交集
  const matchedChild = routerChildren.reduce((found, localChild) => {
    return found || (roleChildrenMap.has(localChild.path)
        ? findValidChild([roleChildrenMap.get(localChild.path)])
        : null);
  }, null);

  // 7. 安全跳转处理
  const targetPath = matchedChild?.urlPath ?? '/404';
  windowPath.value = targetPath;

  // 8. 带错误处理的导航
  router.push(targetPath).catch((error) => {
    console.error('Navigation failed:', error);
    router.push('/error');
  });
};
const isActive = (path: string) => {
  let parts = route.path.split('/');
  let result = '/' + parts[1];
  return result == path;
};
</script>

<style lang="scss" module>
.root {
  width: 100%;
  color: #000;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .lineTop {
    height: 70px;
    display: flex;
    align-items: center;
    background: linear-gradient(to right, #0050A2, #2F94F2);
    /* 标题文字流光效果 */
    .invertedTitle {
      position: relative; /* 关键：为伪元素定位提供基准 */
      display: inline-block; /* 确保伪元素能匹配文字宽度 */
      /* 保留原有文字样式 */
      font-size: 40px;
      font-family: 'YouSheBiaoTiHei', sans-serif;
      color: white; /* 保持原文字颜色 */
      z-index: 99;
      padding-bottom: 5px;
    }
    .showTime {
      color: #fff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      padding-bottom: 5px;
    }
  }


  .menuContainer {
    display: flex;
    align-items: center;
    width: 80vw;
    height: 50px;
    overflow: hidden;
    position: relative;
  }

  .menuWrapper {
    width: 70vw;
  }

  .menuContent {
    display: flex;
    transition: transform 0.3s ease;
  }

  .scrollButton {
    height: 45px;
    width: 35px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border-radius: 5px;
  }

  .scrollButton:hover {
    background-color: #eaeaea;
  }

  .route {
    margin: 0 20px;
    white-space: nowrap;
  }


  @font-face {
    font-family: 'YouSheBiaoTiHei';
    src: url('@/assets/fonts/YouSheBiaoTiHei.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
  }



  img {
    width: 160px;
    height: 37px;
    margin: -10px 15px 0 15px;
  }

  .active {
    font-weight: bold;
    color: #0C75D6;
    position: relative; /* 关键：为伪元素定位提供基准 */

    &::after {
      content: '';
      position: absolute;
      bottom: -7px; /* 调整横线位置（负值表示向下偏移） */
      left: 50%; /* 居中起始点 */
      transform: translateX(-50%); /* 水平居中 */
      width: 60%; /* 横线宽度为元素的60% */
      height: 3px;
      background-color: #0C75D6; /* 横线颜色与文字颜色一致 */
    }
  }

  .userInfo {
    margin-left: 20px;
    height: auto;
    display: flex;
    align-items: center;

    img {
      width: 50px;
      height: 50px;
      cursor: pointer;
      border-radius: 50%;
    }

    .username {
      font-size: 18px;
      padding-right: 15px;
      cursor: pointer;
      white-space: pre-line; /* 保留换行符并换行 */
      line-height: 1.5; /* 可选：调整整体行高 */
      color: #fff;
    }
  }
}
</style>